

import React from 'react'
import {Layout,Row,Col,Card,Form, Icon, Input, Button, Checkbox,Spin,message } from 'antd'
import PureRenderMixin from 'react-addons-pure-render-mixin'
import MMUtile from 'util/mm.jsx'
import User from 'service/user-service.jsx'
import Safty from 'service/safty-service.jsx'
import FooterMsg from 'component/footermsg/index.jsx'


const { Header, Content, Footer, Sider } = Layout; 
const FormItem = Form.Item;
const _mm = new MMUtile();
const _user = new User();
const _safty = new Safty();

class ForgetPSWForm extends React.Component{
	constructor(props){
		super(props);
		this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
		this.state={
			validate:false,
			loading:false,
			phone:'',
			code:'',
			canGetCode:true,
			codenum:120,
			CodeValue:'获取验证码'
		}
	}
	handleSubmit(e){
    e.preventDefault();
    this.setState({
    	loading:true
    })
    this.props.form.validateFieldsAndScroll((err, values) => {
			if(this.timer){
	        clearTimeout(this.timer);
	    }
      if (!err) {
      	_safty.findPassword({
					phone:this.state.phone,
					password:values.password
				}).then((res)=>{
					message.success('恭喜您，修改成功！');
			    this.setState({
			    	loading:false
			    })
					this.props.history.push('/login');
				},(errMsg)=>{
			    this.setState({
			    	loading:false
			    })
					_mm.errorTips(errMsg);
				})
      }else{
      	this.setState({
		    	loading:false
		    })
      }
    });
  }
	getHandleCode(e){
    
    const form = this.props.form;
    const phone = form.getFieldValue('phone');
  	//发送短信验证码接口
  	_user.sendSMS({
			phone:phone
		}).then((res)=>{
      message.success('请在手机上接收并填写验证码');
    },(errMsg)=>{
      _mm.errorTips(errMsg);
      
    })

  	//如果不重复将倒数120秒在按钮上显示
  	if(this.timer){
        clearTimeout(this.timer);
    }
  	this.timer = setInterval(()=>{
  		if(this.state.codenum ===0){
  			//倒数到0，将按钮变为可用
  			this.setState({
					CodeValue:'获取验证码',
					canGetCode:false,
					codenum:120
				})
				clearTimeout(this.timer);
  		}else{
  			//倒数期间，将按钮变为禁用
				this.setState({
					CodeValue:this.state.codenum--+'秒',
					canGetCode:true
				})
  		}

  	},1000);
	}
	checkPhone(rule, value, callback){
    const form = this.props.form;
    const phone = form.getFieldValue('phone')
    if(!(/^1[34578]\d{9}$/.test(phone))){ 
        callback("手机号码有误，请重填");  
    }  else {
    	//校验手机号是否重复
    	_safty.phoneIsExit({
				phone:phone
			}).then((res)=>{
	    	//将手机验证码变为可用
	    	this.setState({
	    		canGetCode:false
	    	})
	      callback();
			},(errMsg)=>{
				_mm.errorTips(errMsg);
			})
    }
  }
	checkPsw(rule, value, callback){
    const form = this.props.form;
    const password = form.getFieldValue('password')
    if(password.length<6 || password.length>20){ 
       callback("密码应为6-20位之间");  
    }  else {
      callback();
    }
  }

	nextEvents(e){
		
    const form = this.props.form;
    const phone = form.getFieldValue('phone');
    const code = form.getFieldValue('code');
		if(!phone){
			message.error('请确认是否输入了手机号')
			return;
		}
    if(!(/^1[34578]\d{9}$/.test(phone))){ 
      message.error('请输入正确的手机号码')
      return ;  
    }
		if(!code){
			message.error('请确认是否输入了验证码')
			return;
		}

		this.setState({
			loading:true
		})
  	//校验手机号
		_safty.codeIsTrue({
			phone:phone,
			code:code
		}).then((res)=>{
			this.setState({
				validate:true,
				loading:false,
				phone:phone
			})
			
		},(errMsg)=>{
				this.setState({
					loading:false
				})
			_mm.errorTips(errMsg)
		})
	}
	render(){
		const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
      },
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0,
        },
        sm: {
          span: 14,
          offset: 6,
        },
      },
    };
    let winheight =document.body.clientHeight;
    let margintop = (winheight-620)>0?(winheight-620)/2:0;
		return(
			<Layout  className="layoutbox">
				<Header  className="headerbox" >
	        <Row >
	          <Col span={24}><img width={300} src={require('img/logo.jpg')} /></Col>
	        </Row>
	      </Header>	
	      <Layout className="layoutbox">
	        <Content className="containerbox" style={{height:winheight-220}}>

						<Form onSubmit={(e)=>{this.handleSubmit(e)}}> 
						<Spin spinning={this.state.loading} size="large">
						{

							!this.state.validate
							?
							<Row style={{marginTop:margintop}}>
		        		<Col span={12}offset={6}>
		        			<Card title="验证手机号" >
		        			<FormItem
					          {...formItemLayout}
					          label={(
					            <span>
					              手机号
					            </span>
					          )}
					          hasFeedback
					        >
					          {getFieldDecorator('phone', {
					            rules: [{ required: true, message: '请输入您的手机号!' },{ validator: this.checkPhone.bind(this) }],
					            value: this.state.phone,
					          })(
					            <Input  />
					          )}
					        </FormItem>
					        <FormItem
					          {...formItemLayout}
					          label="验证码"
					        >
					          <Row gutter={8}>
					            <Col span={12}>
					              {getFieldDecorator('code', {
					                rules: [{ required: true, message: '请输入您获取的验证码!' }],
					            		initialValue: this.state.code,
					              })(
					                <Input   />
					              )}
					            </Col>
					            <Col span={12}>
					              <Button  onClick={this.getHandleCode.bind(this)} disabled={this.state.canGetCode}>{this.state.CodeValue}</Button>
					            </Col>
					          </Row>
					        </FormItem>

						        <FormItem {...tailFormItemLayout}>
											<Button type="primary" onClick={this.nextEvents.bind(this)} >提交</Button>
						        </FormItem>
									</Card>
		        		</Col>
							</Row>
							:
							<Row style={{marginTop:margintop}}>
		        		<Col span={12}offset={6}>
									<Card title="设置新密码" >
										<FormItem
						          {...formItemLayout}
						          label={(
						            <span>
						              新密码
						            </span>
						          )}
						          hasFeedback
						        >
						          {getFieldDecorator('password', {
						            rules: [{ required: true, message:'请输入您的新密码!' },{ validator: this.checkPsw.bind(this) }],
						            value: this.state.password,
						          })(
						            <Input type="password"  placeholder="请输入新密码" />
						          )}
						        </FormItem>	
						        <FormItem {...tailFormItemLayout}>
						          <Button type="primary" htmlType="submit" >提交</Button>
						        </FormItem>
									</Card>
		        		</Col>
							</Row>
						}
    				</Spin>
    				</Form>
	        </Content>
	      </Layout>
      	<Footer className="layoutfooter"><FooterMsg /></Footer>
    	</Layout>
		)
	}
}

const ForgetPSW = Form.create()(ForgetPSWForm)
export default ForgetPSW;